import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Notify } from 'vant'
import request from '@/utils/request'
import RSAEncrypt from '@/utils/RSAEncrypt'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    roles: [],
    permission: { buttons: new Set(), menus: new Map() }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENUS: (state, permissionMenus = []) => {
    var menus = new Map()
    permissionMenus.forEach(item => {
      menus.set(item.code, item)
    })
    state.permission.menus = menus
  },
  SET_PERMISSIONS: (state, permissionButtons = []) => {
    var buttons = new Set()
    permissionButtons.forEach(item => {
      buttons.add(item)
    })
    state.permission.buttons = buttons
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    userInfo.password = RSAEncrypt.encrypt(password)
    userInfo.username = RSAEncrypt.encrypt(username)
    return new Promise((resolve, reject) => {
      request.post('sso/login', {
        username: userInfo.username,
        password: userInfo.password,
        verificationCode: userInfo.verificationCode
      }).then((res) => {
        commit('SET_TOKEN', res)
        setToken(res)
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  },
  // 三方应用授权认证链接
  thirdOauth2Auth({ commit }, params) {
    return new Promise((resolve, reject) => {
      request.post(`sso/third/oauth2Auth`, params).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  modifyUserInfo({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      request.post('sso/modifyUserInfo', userInfo).then((res) => {
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  },
  // 修改密码
  modifyPassword({ commit }, params) {
    return new Promise((resolve, reject) => {
      request.post('sso/modifyPassword', {
        oldPassword: params.oldPassword,
        newPassword: params.newPassword,
        newPasswordAgain: params.newPasswordAgain,
        verificationCode: params.verificationCode
      }).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      request.get('sso/getInfo').then((res) => {
        if (!res) {
          reject('验证失败,请重新登陆!')
        }
        var cacheRoleVos = res.cacheRoleVos
        if (cacheRoleVos && cacheRoleVos.length > 0) { // 验证返回的roles是否是一个非空数组
          const roles = []
          res.cacheRoleVos.forEach((item) => {
            roles.push(item.roleCode)
          })
          commit('SET_ROLES', roles)
        } else {
          Notify({ type: 'danger', message: '当前登陆用户暂未分配角色，请联系管理员' })
          reject('当前登陆用户暂未分配角色，请联系管理员')
        }
        commit('SET_USER_INFO', res)
        commit('SET_PERMISSIONS', res.perms)
        commit('SET_MENUS', res.menuPerms)
        resolve(res)
      }).catch((err) => {
        reject(err)
      })
    })
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      request.post('sso/logout').then(() => {
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch((err) => {
        reject(err)
      })
    })
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  state,
  mutations,
  actions
}

